package com.itheima.controller;

import com.itheima.common.CommonResult;
import com.itheima.common.PageInfo;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import com.itheima.vo.EmployeeVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @author YangJiaHao
 */
@RestController
@RequestMapping("/employee")
@Slf4j
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @PostMapping("/login")
    public CommonResult login(@RequestBody Employee employee) {
        EmployeeVo employeeVo = employeeService.login(employee.getUsername(), employee.getPassword());
        if (employeeVo == null) {
            return CommonResult.error("用户名密码错误");
        }
        return CommonResult.success(employeeVo);
    }

    @GetMapping
    public CommonResult getEmployee() {
        return CommonResult.success("访问成功");
    }

    @PostMapping("/logout")
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        employeeService.clearToken(token);
        return CommonResult.success("退出登录成功");
    }

    @PostMapping
    public CommonResult save(@RequestBody Employee employee) {
        Boolean result = employeeService.save(employee);
        if (!result) {
            return CommonResult.error("新增员工失败");
        }
        return CommonResult.success("新增员工成功");
    }

    @GetMapping("/{id}")
    public CommonResult getById(@PathVariable String id) {
        return CommonResult.success(employeeService.getById(id));
    }

    @GetMapping("/page")
    public CommonResult page(String name,
                             @RequestParam(defaultValue = "1") Integer page,
                             @RequestParam(defaultValue = "10") Integer pageSize) {
        PageInfo<Employee> pageInfo = employeeService.page(name, page, pageSize);
        return CommonResult.success(pageInfo);
    }

    @PutMapping
    public CommonResult updateEmployee(@RequestBody Employee employee) {
        log.info("{}", employee);
        employeeService.updateEmployee(employee);
        return CommonResult.success("员工信息修改成功");
    }
}